# 创建商品编辑页面组件
<template>
  <div class="product-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>编辑商品</span>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品主图" prop="mainImage">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleMainImageChange"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.mainImage" :src="form.mainImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品图片" prop="subImages">
          <el-upload
            v-model:file-list="fileList"
            :auto-upload="false"
            list-type="picture-card"
            :on-change="handleSubImageChange"
            :on-remove="handleSubImageRemove"
            :before-upload="beforeImageUpload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否新品" prop="isNew">
          <el-radio-group v-model="form.isNew">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 商品详情 -->
        <el-divider content-position="left">商品详情</el-divider>
        <el-form-item label="商品描述" prop="detail">
          <el-input
            v-model="form.detail"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getProductDetail, updateProduct, uploadProductImage } from '@/api/product'
import { getCategoryTree } from '@/api/category'

const route = useRoute()
const router = useRouter()
const productId = route.params.id

// 表单数据
const formRef = ref(null)
const form = ref({
  name: '',
  categoryId: '',
  mainImage: '',
  subImages: [],
  detail: '',
  status: 1,
  isNew: 0
})

// 文件列表
const fileList = ref([])

// 分类数据
const categories = ref([])

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  mainImage: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
}

// 获取商品详情
const fetchProductDetail = async () => {
  try {
    const res = await getProductDetail(productId)
    if (res.code === 200 && res.data) {
      const product = res.data
      
      // 处理子图片数据
      let subImages = []
      if (product.subImages) {
        if (typeof product.subImages === 'string') {
          // 如果是字符串，按逗号分割
          subImages = product.subImages.split(',').filter(Boolean)
        } else if (Array.isArray(product.subImages)) {
          // 如果已经是数组，直接使用
          subImages = product.subImages
        }
      }
      
      form.value = {
        name: product.name,
        categoryId: product.categoryId,
        mainImage: product.mainImage,
        subImages: subImages,
        detail: product.detail,
        status: product.status,
        isNew: product.isNew
      }
      
      // 设置图片列表
      fileList.value = subImages.map((url, index) => ({
        name: `商品图片${index + 1}`,
        url
      }))
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoryTree()
    if (res.code === 200 && res.data) {
      categories.value = flattenCategoryTree(res.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 图片上传相关处理
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理主图上传
const handleMainImageChange = async (file) => {
  if (!beforeImageUpload(file.raw)) return
  
  try {
    const res = await uploadProductImage(file.raw)
    if (res.code === 200 && res.data) {
      form.value.mainImage = res.data
      ElMessage.success('主图上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 处理附图上传
const handleSubImageChange = async (file) => {
  if (!beforeImageUpload(file.raw)) return
  
  try {
    const res = await uploadProductImage(file.raw)
    if (res.code === 200 && res.data) {
      form.value.subImages.push(res.data)
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 处理附图删除
const handleSubImageRemove = (file) => {
  const index = form.value.subImages.indexOf(file.url)
  if (index !== -1) {
    form.value.subImages.splice(index, 1)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const submitData = {
      name: form.value.name,
      categoryId: form.value.categoryId,
      mainImage: form.value.mainImage,
      subImages: form.value.subImages,
      detail: form.value.detail,
      status: form.value.status,
      isNew: form.value.isNew
    }
    
    await updateProduct(productId, submitData)
    ElMessage.success('更新成功')
    goBack()
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error(error.message || '更新失败，请检查表单')
  }
}

// 返回列表页
const goBack = () => {
  router.push('/merchant/product/list')
}

// 辅助函数：将分类树扁平化
const flattenCategoryTree = (tree) => {
  const result = []
  const flatten = (items, parentName = '') => {
    items.forEach(item => {
      const fullName = parentName ? `${parentName} / ${item.name}` : item.name
      result.push({
        id: item.id,
        name: fullName
      })
      if (item.children && item.children.length > 0) {
        flatten(item.children, fullName)
      }
    })
  }
  flatten(tree)
  return result
}

onMounted(() => {
  fetchCategories()
  if (productId) {
    fetchProductDetail()
  }
})
</script>

<style scoped>
.product-edit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style> 